"use strict";
const tool = require("../utils/tool");
const _ = require("lodash");
const lightAppDao = require("../dao/light_app_dao");

async function saveLightApp(req, res) {
  const client = tool.getResponseFunc(res);
  try {
    const {userId, domainId, orgId} = tool.getInfoByReq(req);
    const result = await lightAppDao.save({...req.body, userId, domainId, orgId});
    client.success(result);
  } catch (e) {
    client.fail(e);
  }
}

async function deleteLightAppById(req, res) {
  const client = tool.getResponseFunc(res);
  try {
    const result = await lightAppDao.remove({_id: req.params.id});
    client.success(result);
  } catch (e) {
    client.fail(e);
  }
}

async function updateLightAppById(req, res) {
  const client = tool.getResponseFunc(res);
  try {
    const result = await lightAppDao.findOneAndUpdate({
      _id: req.params.id
    }, req.body);
    client.success(result);
  } catch (e) {
    client.fail(e);
  }
}

async function getLightAppById(req, res) {
  const client = tool.getResponseFunc(res);
  try {
    const result = await lightAppDao.findOne({_id: req.params.id});
    client.success(result);
  } catch (e) {
    client.fail(e);
  }
}

async function getLightAppListByUser(req, res) {
  const client = tool.getResponseFunc(res);
  try {
    const {userId, domainId, orgId, isAdmin} = tool.getInfoByReq(req);
    if (!isAdmin) {
      throw new Error("e_not_admin");
    }
    const {pageIndex, pageSize} = tool.getAndValidatePagingParams(req.query);
    const keyword = req.query.keyword || "";
    const total = await lightAppDao.getTotal({orgId, domainId, keyword});
    const list = await lightAppDao.findAndPaging({orgId, domainId, pageIndex, pageSize, keyword});
    client.success({list, total});
  } catch (e) {
    client.fail(e);
  }
}

module.exports = {
  saveLightApp,
  deleteLightAppById,
  updateLightAppById,
  getLightAppById,
  getLightAppListByUser
}
